//统一返回结果中间件
function ResultEntity(code, msg, data) {
  return {
    code,
    msg,
    data
  }
}

let build = function (ctx) {
  let result = {
    ctx: {},
    success(data = {}, msg = "成功", code = 200) {
      this.ctx.body = (ResultEntity(code, msg, data))
    },
    error(msg = "错误", code = 500, data = {}) {
      this.ctx.body = (ResultEntity(code, msg, data))

    }
  }
  result.ctx = ctx
  return result
}

module.exports = async (ctx, next) => {
  ctx.result = build(ctx)
  await next()
}